<template>
  <div>
    <el-dialog title="导入账单" :visible.sync="dialogVisible" :close-on-click-modal="false" :before-close="handleClose">
      <div class="flex-card">
        <div style="flex: 1; display: flex; gap: 15px">
          <el-button type="primary" size="small" @click="downloadTemplate">下载模版</el-button>
          <el-upload action :http-request="handleUploadForm" :show-file-list="false">
            <el-button type="primary" size="small">导入</el-button>
          </el-upload>
        </div>
        <div v-show="countObj.totalNum > 0">
          <span>导入数量：{{ countObj.totalNum }}</span>
          <span>成功：{{ countObj.successNum }}</span>
          <span>失败：{{ countObj.failNum }}</span>
        </div>
      </div>
      <el-form v-if="formData.errList.length > 0" ref="formRef" :model="formData" :rules="rules">
        <el-table :data="formData.errList" border style="margin-top: 15px" max-height="500">
          <el-table-column label="订单号" prop="haOrderCode" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.haOrderCode'" :rules="rules.haOrderCode">
                <el-input v-model="scope.row.haOrderCode" placeholder="请输入订单号" clearable show-word-limit />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="订单金额" prop="totalAmount" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.totalAmount'" :rules="rules.totalAmount">
                <el-input v-model="scope.row.totalAmount" placeholder="请输入订单金额" clearable show-word-limit />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="佣金比例" prop="commissionRate" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.commissionRate'" :rules="rules.commissionRate">
                <el-input v-model="scope.row.commissionRate" placeholder="请输入佣金比例" clearable show-word-limit />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="佣金金额" prop="commissionAmount" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.commissionAmount'" :rules="rules.commissionAmount">
                <el-input v-model="scope.row.commissionAmount" placeholder="请输入佣金金额" clearable show-word-limit />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="付款方式" prop="paymentMode" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.paymentMode'" :rules="rules.paymentMode">
                <el-input v-model="scope.row.paymentMode" placeholder="请输入付款方式" clearable show-word-limit />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="Halyk market的佣金"
            prop="halykMarketCommissionAmount"
            min-width="220"
            :render-header="renderHeader"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="'errList.' + scope.$index + '.halykMarketCommissionAmount'"
                :rules="rules.halykMarketCommissionAmount"
              >
                <el-input
                  v-model="scope.row.halykMarketCommissionAmount"
                  placeholder="请输入Halyk market的佣金"
                  clearable
                  show-word-limit
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="Halyk bank的佣金"
            prop="halykBankCommissionAmount"
            min-width="220"
            :render-header="renderHeader"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="'errList.' + scope.$index + '.halykBankCommissionAmount'"
                :rules="rules.halykBankCommissionAmount"
              >
                <el-input
                  v-model="scope.row.halykBankCommissionAmount"
                  placeholder="请输入Halyk bank的佣金"
                  clearable
                  show-word-limit
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="给合作伙伴的金额" prop="partnerAmount" min-width="220" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.partnerAmount'" :rules="rules.partnerAmount">
                <el-input
                  v-model="scope.row.partnerAmount"
                  placeholder="请输入给合作伙伴的金额"
                  clearable
                  show-word-limit
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="付款日期" prop="payDate" min-width="240" :render-header="renderHeader">
            <template slot-scope="scope">
              <el-form-item :prop="'errList.' + scope.$index + '.payDate'" :rules="rules.payDate">
                <el-date-picker v-model="scope.row.payDate" type="datetime" placeholder="选择日期时间" clearable value-format="yyyy-MM-dd H:m:s"	/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="错误信息" prop="errorInfo" min-width="220" fixed="right" />
          <el-table-column label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button type="danger" size="small" @click="delFn(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <span v-if="formData.errList.length > 0" slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';
export default {
  data() {
    return {
      dialogVisible: false,
      countObj: {
        failNum: 0,
        successNum: 0,
        totalNum: 0,
      },
      formData: {
        errList: [],
      },
      rules: {
        haOrderCode: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
        totalAmount: [{ required: true, message: '请输入订单金额', trigger: 'blur' }],
        commissionRate: [{ required: true, message: '请输入佣金比例', trigger: 'blur' }],
        commissionAmount: [{ required: true, message: '请输入佣金金额', trigger: 'blur' }],
        paymentMode: [{ required: true, message: '请输入付款方式', trigger: 'blur' }],
        halykMarketCommissionAmount: [{ required: true, message: '请输入Halyk market的佣金', trigger: 'blur' }],
        halykBankCommissionAmount: [{ required: true, message: '请输入Halyk bank的佣金', trigger: 'blur' }],
        partnerAmount: [{ required: true, message: '请输入给合作伙伴的金额', trigger: 'blur' }],
        payDate: [{ required: true, message: '请输入付款日期', trigger: 'blur' }],
      },
    };
  },
  methods: {
    renderHeader(h, obj) {
      return h('span', { class: 'cy-table-require' }, obj.column.label);
    },
    handleUploadForm(param) {
      const formData = new FormData();
      formData.append('file', param.file);
      const loading = this.$loading({
        lock: true,
        text: '上传中，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      request({
        url: '/admin/platform/haOrderBill/import',
        method: 'post',
        data: formData,
      })
        .then((res) => {
          loading.close();
          this.handleData(res);
        })
        .finally(() => {
          loading.close();
        });
    },
    downloadTemplate() {
      request({
        url: '/admin/platform/haOrderBill/downloadImportTemplate',
        method: 'get',
        responseType: 'blob',
      }).then((res) => {
        const blob = new Blob([res.file], { type: 'application/octet-stream' }); // res.data为文件流文件
        this.$download.saveAs(blob, res.fileName);
      });
    },
    show() {
      this.dialogVisible = true;
    },
    handleClose() {
      this.formData.errList = [];
      this.countObj = {
        failNum: 0,
        successNum: 0,
        totalNum: 0,
      };
      this.dialogVisible = false;
      this.$emit('getList');
    },
    onSubmit() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)',
          });
          request({
            url: '/admin/platform/haOrderBill/saveBatchBill',
            method: 'post',
            data: { billImportList: this.formData.errList },
          })
            .then((res) => {
              loading.close();
              this.handleData(res);
            })
            .finally(() => {
              loading.close();
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleData(data) {
      if (data.failNum > 0) {
        this.formData.errList = data.errorBillImportRequestList;
        this.countObj = {
          failNum: data.failNum,
          successNum: data.successNum,
          totalNum: data.totalNum,
        };
      } else {
        this.$message.success(this.$t('caoZuoChengGong'));
        this.$emit('getList');
        this.$emit('updata')
        this.handleClose();
      }
    },
    delFn(index) {
      this.formData.errList.splice(index, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
.flex-card {
  display: flex;
  justify-content: space-between;
}

::v-deep {
  .cy-table-require::before {
    content: '*';
    color: red;
  }
}
</style>
